/**
 * This file is part of Wireless TransFer.
 *
 *   Wireless TransFer is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *	
 *   Wireless TransFer is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with Wireless TransFer.  If not, see <http://www.gnu.org/licenses/>.
 *	 
 *	 Copyright (C) 2011
 *   @author christofferP
 */
package com.wirelesstransfer.server.WIFI.handlers;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;

import android.util.Log;

import com.wirelesstransfer.connection.ServerActions;
import com.wirelesstransfer.server.Ifiles;
import com.wirelesstransfer.server.ConnectedClients.ConnectedClient;
import com.wirelesstransfer.server.ConnectedClients.ConnectedClientsHandler;
import com.wirelesstransfer.server.authentication.Code;

/**
 * Select the clients requested files. Creates
 * a new connectedClient with session id
 * files available for this client
 * 
 * Headers needed:
 * authCode
 * sessionId
 * files
 * 
 * @author christofferp
 */

public class SelectFilesHandler extends AbstractHandler {

	private String TAG = "SelectFilesHandler";
	
	private int authCode;
	private String sessionId;
	private String filesStr;
	private List<File> clientFiles;

	private ConnectedClientsHandler connectedClientHandler;
	private Ifiles serverFiles;

	public SelectFilesHandler(Ifiles files){
		this.serverFiles = files;
	}
	
	public void handle(String target,
			Request baseRequest,
			HttpServletRequest request,
			HttpServletResponse response) 
	throws IOException, ServletException {
		Log.v(TAG, "Handling request");

		baseRequest.setHandled(true);

		//Get autheticate code from client and server
		authCode = Integer.parseInt(request.getHeader(ServerActions.AUTHCODE));



		if(Code.validCode(authCode)){
			Log.v(TAG, "Code OK");

			sessionId = request.getHeader(ServerActions.SESSIONID);
			connectedClientHandler = ConnectedClientsHandler.getInstance();
			if(connectedClientHandler.getClientById(sessionId) == null){
				Log.v(TAG, "new client " + sessionId);
				
				filesStr = request.getHeader(ServerActions.FILES);
				
				Log.v(TAG, "Files: \n" + serverFiles.toString());
				Log.v(TAG, "ClientFiles: \n" + filesStr);
				
				String[] clientFilesStr = filesStr.split(":");
				clientFiles = new ArrayList<File>();
				selectFilesFromString(clientFilesStr, serverFiles.getFiles(), clientFiles);
				

				connectClient(request.getLocalAddr(), sessionId, clientFiles);

				Log.v(TAG,connectedClientHandler.getClientById(sessionId).getIP());
				
				response.setStatus(HttpServletResponse.SC_OK);
			}
		}
		else {
			Log.v(TAG, "Code NOT OK");
			response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);			
		}		
	}

	/**
	 * Selects files by name
	 * @param filesStr Array containing filenames
	 * @param files Available files
	 * @param retFiles the file array to save files in
	 */
	private void selectFilesFromString(String[] filesStr, List<File> files, List<File> retFiles){
		for(int i = 0; i < filesStr.length; i++){
			for(int j = 0; j < files.size(); j++){
				if(filesStr[i].equals(files.get(j).getAbsoluteFile().toString())){
					retFiles.add(files.get(j));
					break;
				}
			}
		}
	}

	/**
	 * adds a client to ConnectedClientsHandler with the id returned by this method
	 * @param files, the files on server that is available to the new client
	 * @param sessionId, id of the client
	 * @param ip, clients ip
	 * @return true if client correctly added
	 */
	private boolean connectClient(String ip, String sessionId, List<File> files){
		ConnectedClientsHandler connectedClientHandler = ConnectedClientsHandler.getInstance();
		ConnectedClient client = new ConnectedClient(ip, sessionId, files);
		return connectedClientHandler.addClient(client);
	}

}